# -*- coding: utf-8 -*-
import csv
import re
from apps.news.models import Record
from django.core.management.base import BaseCommand

class Command(BaseCommand):
    def handle(self, *args, **options):
        filename = args[0]
        csv_file = csv.reader(open(filename, 'rb'), delimiter=",")
        regex = re.compile("http\:\/\/smilepost\.ru\/[a-z]+\/([0-9]+)-.+")

        for line in csv_file:
            iteration = 1
            for url in line[1].split("|"):
                if ".html" in url.strip():
                    id = int(regex.findall(url.strip())[0])

                    try:
                        record = Record.objects.get(pk=id)

                        title_data = record.title.split("(")
                        if len(title_data) > 1:
                            title =  u"%s, часть %s (%s" % (title_data[0].strip(), iteration, title_data[1])
                        else:
                            title =  u"%s, часть %s" % (record.title.strip(), iteration)

                        record.title = title
                        record.save()

                        iteration += 1

                    except Exception, e:
                        print e


